/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 * <p>
 * MpmProjectCommunicationService 项目沟通
 * <p>
 * 修改纪录 2021-08-20 版本：1.0 liuchenguang 创建。
 *
 * @version 版本：1.0
 * @author 作者：liuchenguang 创建日期：2021-08-20
 */
package com.topscomm.mpm.service.impl;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.MpmProjectCommunicationEntity;
import com.topscomm.mpm.pojo.MpmProjectEntity;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.DatacodeCache;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.mpm.service.IMpmProjectCommunicationService;
import com.topscomm.mpm.service.impl.auto.MpmProjectCommunicationServiceAuto;
import org.springframework.transaction.annotation.Transactional;

@Service(value = "mpmProjectCommunicationService")
@Scope(value = "singleton")
public class MpmProjectCommunicationService extends MpmProjectCommunicationServiceAuto implements
    IMpmProjectCommunicationService {

    @Autowired
    public MpmProjectService mpmProjectService;
    DatacodeCache datacodeCache = new DatacodeCache();

    /**
     * @param entity
     * @throws ServiceException
     * @author: liuchenguang
     * @date: 2021-8-23
     * @description:编号生成
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity) {
        super.beforeInsert(entity);
        GenerateIDAndCode(entity, MpmSystemConst.CommunicationMeetingPrefix, "ordercode");
    }

    /**
     * @param map
     * @throws ServiceException
     * @author: liuchenguang
     * @date: 2021-9-11
     * @description: 发布会议前生成编号
     */
    protected void updateBefore(Map<String, Object> map) {
        super.updateBefore(map);
        // 判断会议状态是否为1（表示已创建）
        String meetState = ConvertUtil.convertToString(map.get("state"));
        if ("1".equals(meetState)) {
            GenerateCode(map, MpmSystemConst.CommunicationMeetingPrefix, "ordercode");
        }
    }

    /**
     * @param header    : 编号头 如 PP PR PSl
     * @param codeField : 编号列名
     * @return
     * @throws
     * @description:
     * @author liuchenguang
     * @date 2021/9/11
     * @modify
     */
    @Transactional
    public void GenerateIDAndCode(BasicEntity entity, String header, String codeField) {
        try {
            //若id未生成 生成id
            if (entity.getId() <= 0) {
                mpmProjectService.GenerateID(entity);
            }
            long meetId = ConvertUtil.convertToLong(entity.getValue("meetid"));
            String codeFieldStr = ConvertUtil.convertToString(entity.getValue(codeField));
            // 若发布会议，则生成编码
            if (StringUtil.isEmpty(codeFieldStr) && meetId > 0) {
                mpmProjectService.GenerateCode(entity, header, codeField);
            }
        } catch (Exception e) {
            throw new ServiceException(e + "编号生成失败!");
        }
    }

    /**
     * @param
     * @return
     * @throws
     * @description:
     * @author liuchenguang
     * @date 2021/9/11
     * @modify
     */
    private void GenerateCode(Map<String, Object> map, String header, String codeField) {
        // 发布会议前生成编码
        long entityId = ConvertUtil.convertToLong(map.get("id"));
        String docNo = String.valueOf(entityId);
        docNo = docNo.substring(0, 6) + docNo.substring(9);
        try {
            String projectLevel = ConvertUtil.convertToString(map.get("projectlevel"));
            //赋值编号 xxcode
            projectLevel = datacodeCache
                .getValueDynamic("MpmProjectLevel", projectLevel, "code", "name");
            SimpleDateFormat sdFormat = new SimpleDateFormat("yyMMdd");
            String dateCode = sdFormat.format(new Date());
            String flowCode = docNo.substring(docNo.length() - 4);
            header = header + projectLevel + dateCode + flowCode;
            map.put(codeField, header);
        } catch (Exception e) {
            throw new ServiceException(e + "编号生成错误");
        }
    }

    /**
     * @param paraMap
     * @param sqlWhere 转换后的查询语句
     * @return
     * @author: liuchenguang
     * @date: 2021-08-23
     * @description: 获取列表，在管理界面将自己创建的沟通置顶
     * @modify: 2021-9-3
     */
    public ResponseResult<Object> communicationList(Map<String, Object> paraMap, String sqlWhere) {
        paraMap = BaseUtil.decodeSecureMap(paraMap);
        Query query = new Query(paraMap);
        int totalCount = this.getCount(sqlWhere);
        List<Map<String, Object>> tempList = null;
        Map<String, Object> paraMap2 = new HashMap<>();
        int begincount = query.getCurrentPage() * query.getPageSize() - query.getPageSize();
        paraMap2.put("begincount", begincount);
        paraMap2.put("pagesize", query.getPageSize());
        // 重写排序，自己创建的沟通置顶
        String isQuery = ConvertUtil.convertToString(paraMap.get("qry_isQuery"));
        if ("true".equals(isQuery)) {
            // 查询界面下正常排列
            paraMap2.put("sidx", query.getSidx());
        } else {
            // 其他情况下自己创建的沟通置顶
            String userCode = this.getSessionUserBean().getUser().getCode();
            StringBufferProxy sidxSql = new StringBufferProxy(); // 排序语句
            sidxSql.appendLineSingle("case when launchusercode = '{0}' then 0 else 1 end, {1}",
                userCode, query.getSidx());
            paraMap2.put("sidx", sidxSql.toString());
        }
        paraMap2.put("sord", query.getSord());
        paraMap2.put("whereSql", sqlWhere);
        if (query.getPageSize() > 0) {
            tempList = this.queryMapForPage(paraMap2, "queryMapForPage");
        } else {
            tempList = this.queryMap(paraMap2, "queryMapByWhere");
        }
        this.setDispFields(tempList);
        Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
        return ResponseResult.ok(page);
    }

    /**
     * @param mapRow
     * @param datacodeCache
     * @author: liuchenguang
     * @date: 2021-9-3
     * @description:重写setDispFields
     * @modify:
     */
    @Override
    public void setDispFields(Map<String, Object> mapRow, DatacodeCache datacodeCache) {
        super.setDispFields(mapRow, datacodeCache);
        // 配置地点字段显示值
        if (mapRow.get("meetstyle") != null) {
            String meetStyle = ConvertUtil.convertToString(mapRow.get("meetstyle"));
            // 根据会议形式改变地点字段myplace显示
            switch (meetStyle) {
                case "0": // 线上
                    mapRow
                        .put("myplace", ConvertUtil.convertToString(mapRow.get("remotemeetinfo")));
                    break;
                case "1": // 线下
                    mapRow.put("myplace", ConvertUtil.convertToString(mapRow.get("place")));
                    break;
                case "2": // 线上+线下
                    StringBufferProxy myPlace = new StringBufferProxy();
                    myPlace.appendSingle("线上:{0}，线下:{1}",
                        ConvertUtil.convertToString(mapRow.get("remotemeetinfo")),
                        ConvertUtil.convertToString(mapRow.get("place")));
                    mapRow.put("myplace", myPlace.toString());
                    break;
            }
        }
        // 设置权限
        setPermission(mapRow);
    }

    /**
     * @param mapRow 每一行数据
     * @return
     * @author: liuchenguang
     * @date: 2021-9-3
     * @description: 设置编辑权限
     * @modify:
     */
    private void setPermission(Map<String, Object> mapRow) {
        String userCode = this.getSessionUserBean().getUser().getCode(); // 当前用户工号
        String launchUserCode = ConvertUtil.convertToString(mapRow.get("launchusercode")); // 发起人工号
        String projectCode = ConvertUtil.convertToString(mapRow.get("projectcode")); // 项目编号
        // 创建人、运营人员拥有编辑权限
        if (!StringUtil.isEmpty(launchUserCode)) {
            if (this.getSessionUserBean().getUser().getAdminlevel() > 0 || userCode
                .equals(launchUserCode)) {
                mapRow.put("permission", true);
                return;
            }
        }
        // 如果不是创建人或运营人员，则查询是否是项目经理
        StringBufferProxy whereSql = new StringBufferProxy();
        whereSql.appendSingle("enabled = 1 and projectcode = '{0}' and projectmanagercode = '{1}'",
            projectCode, userCode);
        List<Map<String, Object>> projectManagerCodeList = mpmProjectService
            .queryMapFieldsByWhere(whereSql.toString(), Arrays.asList("projectmanagercode"));
        if (projectManagerCodeList.size() > 0) {
            mapRow.put("permission", true);
            return;
        }
        // 如果都不是，权限设置为false
        mapRow.put("permission", false);
    }
}
